<?php

namespace App\Admin\Controllers;

use App\Extensions\Content;
use App\Extensions\EGrid;
use App\Extensions\LinkRowAction;
use App\Http\Controllers\Controller;
use App\PatentApply;
use App\PatentAssess;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class PatentAssessController extends Controller
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected string $title = '专利评估意见';

    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        $patent_apply_id = request()->get('patent_apply_id') ?: 0;
        $model = PatentApply::query()->find($patent_apply_id);
        return $content
            ->isPage()
            ->title($this->title)
            ->description(trans('admin.list'))
            ->body($this->grid($model));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($model)
    {
        $grid = new EGrid(new PatentAssess());
        $grid->model()->where('patent_apply_id', $model['id'])->where('state', 1);
        $grid->column('expert.name', __('评估人'));
        $grid->column('score', __('评分'));
        $grid->column('remark', __('评估意见'))->nowrap(100);
        $grid->disableCreateButton();
        $grid->disableRowSelector();
        $grid->setView('modal.grid-table');
        $grid->actions(function (Grid\Displayers\Actions $actions) use ($model) {
            $actions->disableEdit();
            $actions->disableView();
            $row = $actions->row;
            $actions->prepend(new LinkRowAction([
                [file_custom_preview_url($row['path'], '(评估报告)' . $model['patent_name'], 'show'), '预览'],
                [file_custom_preview_url($row['path'], '(评估报告)' . $model['patent_name']), '下载']
            ]));
        });
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new PatentAssess());
        $form->hidden('state', __('State'));
        $form->file('path', __('附件'));
        return $form;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $model = PatentAssess::query()->find($id);
        $apply = $model->apply ?? null;
        $res = $this->form()->destroy($id);
        if ($apply instanceof PatentApply) {
            $apply->syncScore();
        }
        return $res;
    }
}
